﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using Microsoft.SharePoint.Taxonomy;
using MS.InformationManagement.Presenter.TermsSelector;
using System.Linq;
using System.Text;

namespace MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls
{
    public enum Layout
    {
        Horizontal,
        Vertical
    }

    public partial class TermsSelectors : UserControl, ITermSelectorView
    {

        #region fields

        private TermSelectorPresenter _presenter;
        private TaxonomyFieldValue _selectedTerm;
        private string _selectedCountry;
        private string _selectedState;

        #endregion

        #region Properties

        public Layout Layout
        {
            get { 
                return ViewState["Layout"] == null? MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls.Layout.Vertical: 
                (MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls.Layout)Enum.Parse(typeof(MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls.Layout), ViewState["Layout"].ToString());
            }
            set { 
                ViewState["Layout"] = value;                
            }
        }

        public TermCollection Countries { get; set; }

        public TermCollection States { get; set; }

        public TermCollection Cities
        {
            get
            {
                return Cache["Cities"] as TermCollection;
            }
            set
            {
                Cache["Cities"] = value;
            }
        }

        public TaxonomyFieldValue SelectedTerm
        {
            get
            {
                if (_selectedTerm != null)
                    return _selectedTerm;
                if (Cities == null) return null;
                Term selTerm = (from city in Cities.OfType<Term>()
                                where city.Name == ddlCity.SelectedValue
                                select city).FirstOrDefault();
                if (selTerm == null) return null;
                return TermStoreHelper.GetTaxomyFieldByTerm(selTerm);
            }
            set
            {
                _selectedTerm = value;
            }
        }

        public string SelectedCountry
        {
            get { return (string.IsNullOrEmpty(_selectedCountry)) ? ddlCountry.SelectedValue : _selectedCountry; }
            set { _selectedCountry = value; }
        }

        public string SelectedState
        {
            get { return string.IsNullOrEmpty(_selectedState) ? ddlState.SelectedValue : _selectedState; }
            set { _selectedState = value; }
        }

        public bool Enable
        {
            set
            {
                ddlCity.Enabled = false;
                ddlState.Enabled = false;
                ddlCountry.Enabled = false;
            }
        }

        #endregion

        #region Form Events

        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new TermSelectorPresenter(this);
            if (IsPostBack) return;
            _presenter.HandleLoad();
            
        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            _presenter.LoadStates();
        }

        protected void ddlStates_SelectedIndexChanged(object sender, EventArgs e)
        {
            _presenter.LoadCities();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ddlCountry.Required("Debe seleccionar un país", "ValBtnAddRadicado", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            ddlState.Required("Debe seleccionar un departamento", "ValBtnAddRadicado", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            ddlCity.Required("Debe seleccionar una ciudad", "ValBtnAddRadicado", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);

            switch (Layout)
            {
                case InformationManagerControls.Layout.Vertical:
                default:                    
                    break;
                case InformationManagerControls.Layout.Horizontal:
                    StringBuilder javascript = new StringBuilder("<script type='text/javascript'>$(document).ready(function(){$('#");
                    javascript
                            .Append(UpdatePanel1.ClientID)
                            .Append("').addClass('form-row');")
                            .Append("});</script>");
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "updatepanelfixer", javascript.ToString(), false);
                    break;
            }

            divCountry.Attributes.Add("class", GetLayoutClass());
            divDepartamento.Attributes.Add("class", GetLayoutClass());
            divCiudad.Attributes.Add("class", GetLayoutClass());
        
        }

        #endregion

        #region Implemented Methods

        public void Show()
        {
            initDDlControls(ddlCountry, Countries, SelectedCountry, GlobalConstants.DDL_INITIAL_STATE_COUNTRY);
            initDDlControls(ddlCity, null, "0", GlobalConstants.DDL_INITIAL_STATE_CITY);
            initDDlControls(ddlState, null, GlobalConstants.DDL_INITIAL_STATE_STATE, GlobalConstants.DDL_INITIAL_STATE_STATE);
            if (!string.IsNullOrEmpty(SelectedState))
                initDDlControls(ddlState, States, SelectedState, GlobalConstants.DDL_INITIAL_STATE_STATE);
            if (SelectedTerm != null)
                initDDlControls(ddlCity, Cities, SelectedTerm.Label, GlobalConstants.DDL_INITIAL_STATE_CITY);
        }

        public void ShowStates()
        {
            initDDlControls(ddlState, States, SelectedState, GlobalConstants.DDL_INITIAL_STATE_STATE);
            initDDlControls(ddlCity, null, GlobalConstants.DDL_INITIAL_STATE_CITY, GlobalConstants.DDL_INITIAL_STATE_CITY);
        }

        public void ShowCities()
        {
            string selectedCities = SelectedTerm == null ? default(string) : SelectedTerm.Label[0].ToString();
            initDDlControls(ddlCity, Cities, selectedCities, GlobalConstants.DDL_INITIAL_STATE_CITY);
        }

        #endregion

        #region Private Methods

        private void initDDlControls(DropDownList ddlControl, TermCollection datasource, string selectedValue, string initValue)
        {
            ddlControl.DataSource = datasource;
            ddlControl.DataBind();

            if (!string.IsNullOrEmpty(selectedValue))
                ddlControl.SelectedIndex = ddlControl.Items.IndexOf((from item in ddlControl.Items.OfType<ListItem>()
                                                                     where item.Text == selectedValue
                                                                     select item).FirstOrDefault());
            ddlControl.Items.Insert(0, new ListItem() { Value = "0", Text = initValue });
            ddlControl.CausesValidation = false;

        }

        #endregion

        #region Public Members

        private string GetLayoutClass() {
            string cssClass = string.Empty;
            MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls.Layout seletedLayout = Layout;
            switch (seletedLayout) { 
                case InformationManagerControls.Layout.Horizontal:
                    cssClass = "cell4";
                    break;
                case InformationManagerControls.Layout.Vertical:
                    cssClass = "spaceBottom";
                    break; 
            }
            return cssClass;
        }

        #endregion

    }
}
